﻿using System;
using System.Collections.Generic;
using System.Text;
using SHDocVw;
using mshtml;

namespace EccHttpLib
{
    public class IEInstance
    {
        private const string EqLoacationName = "MatchMail Agent";

        private const string EqLoacationURL = "MatchMail";

        private const string Frame_DataFrm_Lvl_A = "data_frm";

        private const string Frame_Data_Lvl_B1 = "Data";

        private const string Frame_Edit_Lvl_B2 = "Edit";

        //Items
        private const string MAIL_QUESTION = "TEXTAREAQUESTION";
        private const string MAIL_ANSWER = "TEXTAREAANSWER";

        #region Base
        private static ShellWindows ShellWindows
        {
            get { return new ShellWindowsClass(); }
        }
        private IList<IWebBrowser> _instanceList;

        private void GetIEInstances()
        {
            this._instanceList = new List<IWebBrowser>();
            for (int i = 0; i < ShellWindows.Count; i++)
            {

                var wb = ShellWindows.Item(i) as IWebBrowser;//IWebBrowserApp;//IWebBrowser2;//

                if (wb == null)
                    continue;
                try
                {
                    this._instanceList.Add(wb);
                }
                catch (Exception)
                {
                    continue;
                }
            }

            //if (this._instanceList.Count == 0)
            //    this._instanceList = null;
            //return this._instanceList;
        }


        private IWebBrowser FindMailInstance()
        {
            this.GetIEInstances();
            string strType = "";
            foreach (var ins in this._instanceList)
            {
                try
                {
                    if (ins.LocationName.Contains(EqLoacationName)
                        && ins.LocationURL.Contains(EqLoacationURL))
                    {
                        strType = ins.Type;
                        return ins;
                    }

                }catch(Exception e)
                {
                    continue;
                }
                
            }
            return null;
        }
#endregion

        #region GetFrames
        private IList<HTMLWindow2Class> GetFrames(HTMLDocument pHtmlDocument)
        {

            var length = pHtmlDocument.frames.length;
            IList<HTMLWindow2Class> list = new List<HTMLWindow2Class>();
            for (var i = 0; i < length; i++)
            {
                list.Add(pHtmlDocument.frames.item(i) as HTMLWindow2Class);
            }

            return list;
        }

        private HTMLDocument GetDataFrm_LevelA()
        {
            IWebBrowser wb = this.FindMailInstance();

            if (wb.Document == null)
                throw new Exception("Cann't Find MatchMail Agent Window!");//return null;

            foreach (var frm in this.GetFrames(wb.Document as HTMLDocument))
            {
                if (Frame_DataFrm_Lvl_A.Equals(frm.name))
                {
                    return frm.document as HTMLDocument;
                }
            }

            return null;
        }

        private HTMLDocument Get_Data_LevelB1(HTMLDocument doc_lvl_a)
        {

            foreach (var frm in this.GetFrames(doc_lvl_a))
            {
                if (Frame_Data_Lvl_B1.Equals(frm.name))
                {
                    return frm.document as HTMLDocument;
                }
            }

            return null;
        }

        private HTMLDocument Get_Edit_LevelB2(HTMLDocument doc_lvl_a)
        {

            foreach (var frm in this.GetFrames(doc_lvl_a))
            {
                if (Frame_Edit_Lvl_B2.Equals(frm.name))
                {
                    return frm.document as HTMLDocument;
                }
            }

            return null;
        }
        #endregion

        private String GetAttributeById(HTMLDocument _htmlDocument,string idValue,string attributeValue)
        {
            String str = "";

            if(_htmlDocument == null
                ||_htmlDocument.getElementById(idValue)== null
                ||_htmlDocument.getElementById(idValue).getAttribute(attributeValue) == null)
                return str;

            return _htmlDocument.getElementById(idValue).getAttribute(attributeValue).ToString();

        }

        private String GetAttributeByNameIndex(HTMLDocument _htmlDocument, string nameValue,int index, string attributeValue)
        {
            String str = "";

            if (_htmlDocument == null
                ||_htmlDocument.getElementsByName(nameValue) == null
                ||_htmlDocument.getElementsByName(nameValue).length <= index)
                return str;

            var htmlElement = _htmlDocument.getElementsByName(nameValue).item(index) as IHTMLElement;

            if (htmlElement == null || htmlElement.getAttribute(attributeValue) == null)
                return str;

            return htmlElement.getAttribute(attributeValue).ToString();

        }


        public IDictionary<string,string> GetInfo()
        {
            HTMLDocument htmlDocument = this.GetDataFrm_LevelA();

            if (htmlDocument == null)
                throw new Exception("Cann't Find data_frm Frame!");//return null;


            HTMLDocument htmlDocumentb1 =
            this.Get_Data_LevelB1(htmlDocument);//Data

            HTMLDocument htmlDocumentb2 =
            this.Get_Edit_LevelB2(htmlDocument);//Edit

            Dictionary<string,string> _dictionary = new Dictionary<string, string>();

            //Edit

            //Question   

            _dictionary.Add(
            "TEXTAREAQUESTION",
            this.GetAttributeById(htmlDocumentb2,"TEXTAREAQUESTION","value"));

            //Answer
            _dictionary.Add(
            "TEXTAREAANSWER"
            ,this.GetAttributeById(htmlDocumentb2,"TEXTAREAANSWER","value"));

            //Memo 
            _dictionary.Add(
            "TEXTAREAMEMO"
            ,this.GetAttributeById(htmlDocumentb2,"TEXTAREAMEMO","value"));

            //CategoryName
            String str = this.GetAttributeById(htmlDocumentb2,"IMGSUBJECT","alt");
            String strCategoryFull = str; 
            if(!"".Equals(str))
            {
                int idx_start = str.IndexOf("【");
                int idx_end = str.IndexOf("】");
                str = str.Substring(idx_start, idx_end - idx_start + 1);


                idx_start = strCategoryFull.IndexOf("カテゴリ　		：[");
                strCategoryFull = strCategoryFull.Substring(idx_start);
                idx_end = strCategoryFull.IndexOf("]");

                strCategoryFull = strCategoryFull.Substring(0, idx_end).Replace("カテゴリ　		：[","");
            }
            _dictionary.Add(
            "CategoryName"
            , str);

            _dictionary.Add(
            "CategoryNameFull"
            , strCategoryFull);

            //Data
            //IHTMLElement _htmlElement;
            //案件番号
            _dictionary.Add("CntNo",this.GetAttributeByNameIndex(htmlDocumentb1,"CntNo",0,"value"));

            //RcvDate
            _dictionary.Add("RcvDate",this.GetAttributeByNameIndex(htmlDocumentb1,"RcvDate",0,"value"));

            return _dictionary;
        }

        public bool setAnswer(string str)
        {
            HTMLDocument htmlDocument = this.GetDataFrm_LevelA();

            if (htmlDocument == null)
                return false;

            HTMLDocument htmlDocumentb2 =
            this.Get_Edit_LevelB2(htmlDocument);//Edit

            htmlDocumentb2.getElementById("TEXTAREAANSWER").setAttribute("value",str);
            return true;
        }

        public bool setMemo(string str)
        {
            HTMLDocument htmlDocument = this.GetDataFrm_LevelA();

            if (htmlDocument == null)
                return false;

            HTMLDocument htmlDocumentb2 =
            this.Get_Edit_LevelB2(htmlDocument);//Edit

            htmlDocumentb2.getElementById("TEXTAREAMEMO").setAttribute("value", str);
            return true;
        }

    }
}
